package com.zz.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zz.common.R;
import com.zz.entity.LoggingEvent;
import com.zz.mapper.LoggingEventMapper;
import com.zz.service.LoggingEventService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;

import javax.annotation.Nullable;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * slf4j框架日志Service实现
 *
 * @author 朱彦燕
 */
@Service
@Validated
public class LoggingEventServiceImpl extends ServiceImpl<LoggingEventMapper, LoggingEvent> implements LoggingEventService {

    @Autowired
    private LoggingEventMapper loggingEventMapper;

    @Override
    public R<Page> logEvent(int page, int pageSize, @Nullable String startTime, @Nullable String endTime) throws ParseException {
        // 条件过滤器
        LambdaQueryWrapper<LoggingEvent> wrapper = new LambdaQueryWrapper<>();
        // 按创建时间降序排序
        wrapper.orderByDesc(Boolean.parseBoolean("timestmp"));

        // 时间转化格式
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        // 将字符串转为时间
        if (!StringUtils.isEmpty(startTime)){
            Date date = simpleDateFormat.parse(startTime);
            long sTime = date.getTime();
            // 大于等于
            wrapper.ge(LoggingEvent::getTimestmp, sTime);
        }
        if (!StringUtils.isEmpty(endTime)){
            Date date = simpleDateFormat.parse(endTime);
            long eTime = date.getTime();
            // 小于等于
            wrapper.le(LoggingEvent::getTimestmp, eTime);
        }

        Page<LoggingEvent> pageInfo = new Page<>(page, pageSize);
        Page<LoggingEvent> pages = loggingEventMapper.selectPage(pageInfo, wrapper);

        return R.success(pages);
    }
}
